<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/layouts/include/taglib.jsp" %>

<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8">
<meta name="decorator" content="default" />
</head>

<body>
	<div class="row">
		<div class="col-md-4">
			<div class="widget-box">
				<div class="widget-header header-color-blue2">
					<h4 class="lighter smaller">菜单树</h4>
				</div>

				<div class="widget-body">
					<div class="widget-main padding-8">
						<div id="buttons">
							<button class="btn btn-success btn-sm" onclick="addMenu();"><i class="icon-plus-sign"></i>新增</button>
							<button class="btn btn-danger btn-sm" onclick="delMenu();"><i class="icon-remove"></i>删除</button>
						</div>
						<div class="hr hr-18 dotted hr-double"></div>
						<div id="menuTree" class="ztree"></div>
					</div>
				</div>
			</div>
		</div>
		<div class="col-md-7">
			<div class="widget-box">
				<div class="widget-header">
					<h4>菜单详细信息</h4>
				</div>
				<div class="widget-body">
					<div class="widget-main no-padding">
						<form class="form-horizontal" role="form" id="menuEditForm" method="post">
							<fieldset>
								<div class="form-group sr-only">
								 	<label class="col-md-3 control-label" for="id">id</label>
								  	<div class="col-md-9">
										<input type="text" id="uuid" name="uuid" placeholder="ID" class="form-control">
										<!-- <input type="text" id="parentMenuId" name="parentMenuId" class="form-control"/> -->
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="parentMenuId">父级菜单名称</label>
								  	<div class="col-md-9">
										<select class="width-95 select2" id="parentMenuId" name="parentMenuId" data-placeholder="父级菜单名称">
											
										</select>
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="menuName">菜单名称</label>
								  	<div class="col-md-9">
										<input type="text" id="menuName" name="menuName" placeholder="菜单名称" class="form-control input-sm">
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="menuType">类型</label>
							  		<div class="col-md-9">
										<select class="width-95 select2" id="menuType" name="menuType" data-placeholder="菜单类型">
											<option value="1">菜单</option>
											<option value="2">按钮</option>
										</select>
							  		</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" id="setMenuLabel" for="menuUri">菜单uri</label>
								  	<div class="col-md-9">
										<input type="text" id="menuUri" name="menuUri" placeholder="菜单uri" class="form-control input-sm">
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="menuIco">菜单图标</label>
								  	<div class="col-md-9">
										<input type="text" id="menuIco" name="menuIco" placeholder="菜单图标" class="form-control input-sm">
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="menuOrder">菜单顺序</label>
								  	<div class="col-md-9">
										<input type="text" id="menuOrder" name="menuOrder" placeholder="菜单顺序" class="form-control input-sm">
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="show">是否显示</label>
								  	<div class="col-md-9">
											<select class="width-95 select2" id="isShow" name="isShow" data-placeholder="菜单类型">
												<option value="Y">是</option>
												<option value="N">否</option>
											</select>
								  	</div>
								</div>
								<div class="form-group">
								  	<label class="col-md-3 control-label no-padding-right" for="menuTrip">菜单提示</label>
								  	<div class="col-md-9">
										<input type="text" id="menuTrip" name="menuTrip" placeholder="菜单提示" class="form-control input-sm">
								  	</div>
								</div>
							</fieldset>
							<div class="form-actions center">
								<button type="submit" class="btn btn-sx btn-success">
									<i class="icon-save icon-on-left"></i>保存
<!-- 									<i class="icon-arrow-right icon-on-right bigger-110"></i> -->
								</button>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>


<!-- 
<script src="${ctx}/static/ace/assets/js/chosen.jquery.min.js"></script>
 -->
<!-- tree  fuelux -->
<script src="${ctx}/static/ace/assets/js/fuelux/fuelux.tree.min.js"></script>
<script>
var menuTree,options;

var treeObj;
var treeNodes;
var setting = {
	check: {
		enable: false
	},
	data : {
		simpleData : {
			enable : true,
			idKey : "uuid",
			pIdKey : "parentMenuId"
		}
	},
	 async : {
		enable : true,
		url : "${ctx}/sys/menu/getAllChildMenuList.do",
		type:"post",
		autoParam : ["uuid"],
		//otherParam:{"otherParam":"zTreeAsyncTest"},
		dataFilter : filter
	}, 
	view : {
		selectedMulti : false
	} ,
	callback : {
		onAsyncSuccess : zTreeOnAsyncSuccess,
		onClick : zTreeOnClick
	}
};

function filter(treeId, parentNode, childNodes) {
	if (!childNodes)
		return null;
	for (var i = 0, l = childNodes.length; i < l; i++) {
		if(childNodes[i].menuName != null) {
			childNodes[i].name = childNodes[i].menuName.replace(/\.n/g, '.');
		}
	}
	return childNodes;
};

function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
	//treeObj.expandAll(true);
	/* var nodes = treeObj.transformToArray(treeObj.getNodes());
	for (var i = 0; i < nodes.length; i++) {
		var node = nodes[i];
		if (node.parentOrgNo == "" || node.parentOrgNo == "10099") {
			treeObj.expandNode(node);
		}
	} */
	//让页面滚动条定位到顶部
	document.documentElement.scrollTop = 0; //IE
	document.body.scrollTop = 0; //Firefox
};
function zTreeOnClick(event, treeId, treeNode) {
	 getMenuById(treeNode.uuid);
     $('#menuEditForm').data('bootstrapValidator').resetForm();//重置表单验证
};

//菜单保存验证选项配置 
options = {
		message: '信息填写不完整',
		submitHandler: function(validator, form, submitButton) {
			Otod.ajax({
				url:"${ctx}/sys/menu/save.do",
				data: form.serialize(),
				contentType: "application/x-www-form-urlencoded;",
				successFn: function(data){
					var selectedNodes = treeObj.getSelectedNodes();
					if(selectedNodes.length>0){
						treeObj.reAsyncChildNodes(selectedNodes[0].getParentNode(), "refresh");
					}else{
						treeObj.reAsyncChildNodes(null, "refresh");
					}
					$('#menuEditForm')[0].reset();
					getMenuList();
					Otod.Msg.info(data.info);
                 }
			 });
        },
        fields: {
        	menuName:{
        		message:'菜单名称不能为空',
        		validators:{
        			notEmpty: {
                        message: '菜单名称不能为空'
                    }
        		}
        	},
        	menuUri:{
        		message:'菜单Uri不能为空',
        		validators:{
        			notEmpty: {
                        message: '菜单Uri不能为空'
                    }
        		}
        	},
        	menuOrder:{
        		message:'菜单顺序为数字',
        		validators:{
        			digits:{
        				message:'菜单顺序为数字',
        			}
        		}
        	}
        }
};

$("#parentMenuId")
.on("change", function() { 
	if($("#parentMenuId option:selected").val() == $("#uuid").val()){
		Otod.Msg.warn("不能选择自身作为父级，请重新选择！");
		$("#parentMenuId").select2("val", "");
	}else{
	 $("#parentMenuId").select2("val", $("#parentMenuId option:selected").val());
	}
});

$("#menuType")
.on("change", function() { 
	if($("#menuType option:selected").val() == "2"){
		$("#setMenuLabel").text("权限Id");
	}else{
		$("#setMenuLabel").text("菜单uri");
	}
});

function getMenuList(){
	Otod.ajax({
		url:"${ctx}/sys/menu/getMenuList.do",
		//contentType: "application/x-www-form-urlencoded;",
		successFn:function(data){
			var html = "<option value=''>"+"创建顶级菜单"+"</option>";
			for(var i=0;i<data.length;i++){
				html =  html +  "<option value=\""+data[i].uuid+"\">"+data[i].menuName+"</option>";
			}
			$("#parentMenuId").html(html);
		}
	 });
}

//菜单添加事件 
function addMenu(){
	//重置表单 
	$('#menuEditForm')[0].reset();
	if(treeObj.getSelectedNodes().length>0){//如果有选中的节点，表单父菜单ID赋值 
		var options = $("#parentMenuId option");
		if(treeObj.getSelectedNodes()[0].menuType == "2"){
			Otod.Msg.warn("按钮下不能添加新的按钮或菜单！");
			$("#parentMenuId").select2("val", "");
		}
		 else{
			$.each(options,function(index,item){
				if(item.value == treeObj.getSelectedNodes()[0].uuid){
					 $("#parentMenuId").select2("val", treeObj.getSelectedNodes()[0].uuid);
				}
			});
		} 
	}
}

//菜单删除事件 
function delMenu(){
	var selectedItem = treeObj.getSelectedNodes();
	if(selectedItem.length <= 0){
		Otod.Msg.warn('请选择要删除的记录');
		return;
	}
	if(selectedItem[0].type == 'folder'){
		Otod.Msg.warn('此菜单含有子菜单，请先删除子菜单');
		return;
	}
	
	Otod.Msg.confirm("确定要删除该信息吗？","删除菜单",deleteSelectedMenu);
	
	
	
}

function deleteSelectedMenu(){
	var selectedItem = treeObj.getSelectedNodes();
	 Otod.ajax({
			url:"${ctx}/sys/menu/deleteById.do",
			data: selectedItem[0].uuid,
			successFn: function(data){
				treeObj.removeNode(selectedItem[0]);
	            Otod.Msg.info('删除成功！');
	            $('#menuEditForm')[0].reset();
	            //TODO：如果是子节点删除，父节点只有一个的时候父节点样式修改数据data为null修改 
			}
		}); 
}

//菜单查询事件：根据菜单ID查询菜单详细信息
function getMenuById(id){
	Otod.ajax({
		url:"${ctx}/sys/menu/getMenuById.do",
		data:id,
		successFn: function(data){
			 	for(var d in data){
					 if($("#"+d).is('select')){
						 $("#"+d).select2("val",data[d]); 
						 $("#parentMenuId").select2("val", data.parentMenuId);
					 }else{
					 	$("#"+d).val(data[d]);
					 }
			 	}
			 	
			 	if($("#menuType").val() == "2" ){
			 		$("#setMenuLabel").text("权限Id");
			 	}else{
			 		$("#setMenuLabel").text("菜单uri");
			 	}
		}
	 });
}
		 

//==============fuel ux菜单树 
var DataSource = function (options) {
	this._data = options.data;
};

DataSource.prototype = {
	data: function (options, callback) {
		callback({ data: options.data || this._data });
	}
};

$(document).ready(function() {
		

		/*  Otod.ajax({
			url:"${ctx}/sys/menu/getAllMenuList.do",
			successFn: function(data){
				treeNodes = data;
	         	
			}
		 });  */
		 treeObj = $.fn.zTree.init($("#menuTree"), setting);
		
		 getMenuList();
		
		/*
		//new Otod.data.Store({ url: '${ctx}/sys/menu/getAllMenu.do' });
		menuTree = $('#menuTree').ace_tree({
			dataSource :  new Otod.data.Store({ url: '${ctx}/sys/menu/getAllMenu.do' }),
			multiSelect:false,
			loadingHTML:'<div class="tree-loading"><i class="icon-refresh icon-spin blue"></i></div>',
			'open-icon' : 'icon-minus',
			'close-icon' : 'icon-plus',
			'selectable' : true,
			'selected-icon' : 'icon-ok',
			'unselected-icon' : 'icon-remove'
		});
		*/
		
		
		//菜单节点选中事件 
		$('#menuTree').on('selected', function (evt, data) {
	        //加载表单信息
	        getMenuById(treeObj.getSelectedNodes()[0].uuid);
	        $('#menuEditForm').data('bootstrapValidator').resetForm();//重置表单验证
	    });
		
		//父节点展开事件
		/* $('#menuTree').on('opened', function (evt, data) {
	        //加载表单信息 
	        getMenuById(data.id);
	        $('#menuEditForm').data('bootstrapValidator').resetForm();//重置表单验证
	        //如果有选中的节点，节点取消选中样式
	        if(menuTree.tree('selectedItems').length>0){
	        	var selectedIetem = menuTree.tree('selectedItems');
	        	var $itemEl = $(this).find("div.tree-item-name").filter(function (_, treeItem) {
	                return $(treeItem).text() == selectedIetem[0].name;
	            }).parent();
	        	$itemEl.find("i").attr('class','icon-remove');
	        }
	        $("div.tree-selected").removeClass('tree-selected');//移除所有选中节点样式,父节点
	        //树父节点选中 添加选中样式 
	        var $folderSelected = $(this).find("div.tree-folder-name").filter(function (_, treeFolder) {
                return $(treeFolder).text() == data.name;
            }).parent();
	        $folderSelected.addClass('tree-selected');
	    }); */
		
		//父节点关闭事件 
		$('#menuTree').on('closed', function (evt, data) {
			$('div.tree-folder-header.tree-selected').removeClass('tree-selected');
		});
		
		//初始化下拉控件
		$(".select2").select2(); 
		
		//验证
		$('#menuEditForm').bootstrapValidator(options);
		/*$('button[type="submit"]').click(function(){ //在ie,firefox下表单会重复提交 google下不会
			$('#menuEditForm').bootstrapValidator('validate');
		});*/
	});
</script>
</body>
</html>